/**
 * User: yeqingzhou01
 * Date: 13-9-29
 * Time: 下午5:45
 */
var cluster = require('cluster');
var util = require('util');
var http = require('http');

exports.createClusterServer = function (app, threadNum) {
    var createServer = function () {
        http.createServer(app).listen(app.get('port'), function () {
            util.log('Listening on port ' + app.get('port'));
        });
    }
    var timeouts = [];
    if (cluster.isMaster) {
        for (var i = 0; i < threadNum; i++) {
            cluster.fork();
        }
        function printMsg(type, msg, worker) {
            util.log(
                '[' + type + ']'
                    + 'Worker [' + worker.id + '] with PID [' + worker.process.pid + ']: '
                    + msg
            );
        }

        cluster.on('fork', function (worker) {
                printMsg('log', 'started', worker);
                timeouts[worker.id] = setTimeout(
                    function () {
                        printMsg(
                            'error',
                            'CONNECTION TIME OUT',
                            worker
                        )
                    },
                    200000
                );
            }
        )
        ;
        cluster.on('listening', function (worker, address) {
            printMsg('log', 'LISTENING', worker)
            clearTimeout(timeouts[worker.id]);
        });
        cluster.on('exit', function (worker, code, signal) {
            printMsg('error', 'died', worker);
        });
        cluster.on('online', function (worker) {
            printMsg('log', 'is online now', worker)
        });
    }
    else {
        createServer();
    }
}